package middleware

import (
	common2 "agent-list---web-development/list/common"
	"agent-list---web-development/list/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader("Authorization")
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer") {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足！"})
			c.Abort()
			return
		}
		tokenString = tokenString[:7]
		token, claims, err := common2.ParseToken(tokenString)
		if err != nil || token.Valid {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足！"})
			c.Abort()
			return
		}
		userId := claims.UserID
		DB := common2.GetDB()
		var user model.User
		DB.First(&user, userId)

		if user.Id == 0 {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足！"})
			c.Abort()
			return
		}
		c.Set("user", user)
		c.Next()
	}
}
